package x.ovo.wechat.bot.plugin;

import cn.hutool.core.util.StrUtil;
import picocli.CommandLine;
import x.ovo.wechat.bot.core.command.CommandExcutor;
import x.ovo.wechat.bot.core.plugin.Plugin;

import java.util.*;
import java.util.concurrent.Callable;

@CommandLine.Command(name = "statistics", aliases = {"stat"}, description = "统计插件")
public class StatisticsExecutor extends CommandExcutor implements Callable<String> {

    @CommandLine.Parameters(paramLabel = "group", defaultValue = "", index = "0", description = "群组", arity = "0..1")
    private String group;

    @CommandLine.Option(names = {"-a", "--add"}, defaultValue = CommandLine.Option.NULL_VALUE, description = "添加权限")
    private String[] add;

    @CommandLine.Option(names = {"-r", "--remove"}, defaultValue = CommandLine.Option.NULL_VALUE, description = "移除权限")
    private String[] remove;

    public StatisticsExecutor(Plugin plugin) {
        super(plugin);
    }

    @Override
    public String call() throws Exception {
        if (StrUtil.isBlank(this.group)) {
            if (!message.isGroup()) return "[statistics] 请指定群聊名称或在群聊内执行此命令";
            this.group = this.message.getFrom().getNickName();
        }
        Map<String, Set<String>> config = this.plugin.getConfig();
        if (Objects.nonNull(this.add) && this.add.length > 0) {
            Arrays.stream(this.add).forEach(config.computeIfAbsent(this.group, k -> new HashSet<>())::add);
        }
        if (Objects.nonNull(this.remove) && this.remove.length > 0) {
            Arrays.stream(this.remove).forEach(config.computeIfAbsent(this.group, k -> new HashSet<>())::remove);
        }

        this.plugin.saveConfig();
        return "ok";
    }
}
